package com.m3839.sdk.pay.task;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

/**
 * @author ChenBaoyang
 * @description: IPollingTask
 * @date 2021/12/9 16:32
 */
public abstract class IPollingTask {

    /** handler消息 */
    protected static final int MSG_POLLING = 101;

    /** 轮询间隔 */
    protected static final int POLLING_INTERVAL = 1000;

    /** 轮询的最大次数 */
    protected static final int POLLING_MAX_TIME = 5;

    /** 统计轮询的次数 */
    protected int count;

    protected boolean isRunning = false;

    /**
     * 开始轮询操作
     */
    public void startPollingOrder() {
        if(isRunning) {
            return;
        }
        isRunning = true;
        handler.removeMessages(MSG_POLLING);
        handler.sendEmptyMessageDelayed(MSG_POLLING, POLLING_INTERVAL);
    }


    protected final Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MSG_POLLING && betweenPollStage()) {
                doWork();
                count++;
            }
        }
    };

    protected abstract void doWork();

    protected boolean betweenPollStage() {
        return count < POLLING_MAX_TIME;
    }




}
